package org.itboys.interceptor;

import org.itboys.admin.common.SystemLoginUserPermission;
import org.itboys.admin.service.AdminUserService;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.framework.spring.interceptor.ServletContextInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Mloong
 * @author weisky
 * @date 2016/8/11
 */
public class AdminIntercepter extends ServletContextInterceptor {

    protected Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 是否开启接口的权限校验。
     * 开启。自行删除后台角色管理页面。template\screen\ace\sys\role-list.vm中【分配菜单权限】按钮
     * 关闭。自行删除后台角色管理页面。template\screen\ace\sys\role-list.vm中【分配功能权限】按钮
     */
    public static boolean is_open_operate_permission_check=false;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private AdminUserService adminUserService;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        request.setAttribute("staticRoot", resourceHolder.getStringValue("staticRoot"));
        request.setAttribute("adminRoot", resourceHolder.getStringValue("adminRoot"));
        request.setAttribute("imgRoot", resourceHolder.getStringValue("imgRoot"));
        request.setAttribute("mobileRoot", resourceHolder.getStringValue("mobileRoot"));
        //2017年3月14日，江雄
        request.setAttribute("dictionaryRoot", resourceHolder.getStringValue("dictionaryRoot"));
        request.setAttribute("dictionaryRootMuilt", resourceHolder.getStringValue("dictionaryRootMuilt"));



        String url = request.getRequestURI();
        System.out.println("本次请求地址="+url);

        /**校验接口权限**/
        if(is_open_operate_permission_check){
            System.err.print("本次用户权限"+ ListUtil.isNotNull(SystemLoginUserPermission.loginUserOperatePermssion));
            if(ListUtil.isNotNull(SystemLoginUserPermission.loginUserOperatePermssion)) {
                for (SystemLoginUserPermission per : SystemLoginUserPermission.loginUserOperatePermssion) {
                    //System.err.print("用户=" + per. () + ",接口地址= " + per.getUrl());

                }

            }
        }
            //2019年1月21日15:27:41，增加系统是否登陆权限
            if(url.startsWith("/sunday/web")||
                    url.startsWith("/ace/system")){
                Object loginUserId = request.getSession().getAttribute("au");
                logger.info("----session中获取登陆用户-----"+ loginUserId);
                if(loginUserId == null){
                    response.sendRedirect("/");
                    return false;
                }

        }
        return super.preHandle(request, response, handler);
    }
}
